// pages/room/room.js
var QQMapWX = require('./qqmap-wx-jssdk.js');

// 实例化路线规划 API 核心类
var qqmapsdk = new QQMapWX({
  key: 'QQKBZ-STDR6-O44SW-E5ECG-H3LQV-BEFGJ' // 必填
});

Page({

  /**
   * 页面的初始数据
   */
  data: {
    user: {},
    markers: [],
    polyline: [],
    avatars: [],
    select_id: -1,
    room_id: null,
    user_id: null,
    // 定时器
    timer: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var _this = this
    this.setData({
      room_id: options.room_id,
      user_id: options.user_id
    })
    // 获取当前经纬度
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        _this.setData({
          user: {
            latitude: res.latitude,
            longitude: res.longitude,
          },
          timer: setInterval(() => {
            _this.updateLocation();
          }, 5000)
        });
        _this.updateLocation();
      }
    })
  },

  // 页面关闭
  onHide: function () {
    var _this = this;
    clearInterval(this.data.timer);
    wx.request({
      url: 'https://inkghost.xyz/api/room/leave',
      data: {
        room_id: _this.data.room_id,
        user_id: _this.data.user_id
      },
      method: 'POST',
      success(res) {
        if (!res.success) {
          wx.showToast({
            title: res.msg,
            icon: 'error',
            duration: 2000
          })
        }
      }
    })
  },

  // 更新用户地理坐标
  updateLocation: function () {
    var _this = this;
    wx.request({
      url: 'https://inkghost.xyz/api/location',
      data: {
        room_id: _this.data.room_id,
        user_id: _this.data.user_id,
        location: _this.data.user
      },
      method: 'POST',
      success(res) {
        if (res.success) {
          setData({
            markers: res.markers,
            avatars: res.avatars
          })
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'error',
            duration: 2000
          })
        }
      }
    })
  },

  // 更新目标对象
  updateTarget: function (e) {
    this.setData({
      select_id: e.currentTarget.dataset.id
    })
    this.rotePlaning()
  },

  // 规划目标路线
  rotePlaning: function () {
    var _this = this;
    var target = null;

    this.data.markers.forEach((item) => {
      if (item.id === _this.data.select_id) {
        target = item;
      }
    })

    if (target === null) {
      wx.showToast({
        title: '该用户已退出',
        icon: 'error',
        duration: 2000
      })
      _this.setData({
        polyline: []
      })
      return;
    }

    //调用距离计算接口
    qqmapsdk.direction({
      mode: 'walking',
      from: this.data.user,
      to: {
        latitude: target.latitude,
        longitude: target.longitude
      },
      success: function (res) {
        console.log(res);
        var ret = res;
        var coors = ret.result.routes[0].polyline,
          pl = [];
        //坐标解压（返回的点串坐标，通过前向差分进行压缩）
        var kr = 1000000;
        for (var i = 2; i < coors.length; i++) {
          coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
        }
        //将解压后的坐标放入点串数组pl中
        for (var i = 0; i < coors.length; i += 2) {
          pl.push({
            latitude: coors[i],
            longitude: coors[i + 1]
          })
        }
        console.log(pl)
        //设置polyline属性，将路线显示出来,将解压坐标第一个数据作为起点
        _this.setData({
          polyline: [{
            arrowLine: true,
            color: "#11ca53",
            points: pl,
            width: 4
          }]
        })
      },
      fail: function (error) {
        console.error(error);
      },
      complete: function (res) {
        console.log(res);
      }
    });
  },

  // 分享页面
  onShareAppMessage() {
    return {
      title: '加入位置共享',
      path: '/index/index?room_id=33025',
    }
  }
})